from django.contrib.auth import authenticate, login, logout
from django.http import HttpResponse, HttpResponseRedirect
from django.template.loader import get_template
from django.template import Context


def login_page(request):
   t = get_template('registration/login.html') 
   next_url = ''
   if request.GET.has_key('next'):
       next_url = request.GET['next']

   return HttpResponse(t.render(Context({'next': next_url})))

def login_handler(request):
    username = request.POST['username']
    password = request.POST['password']
    user = authenticate(username=username, password=password)
    if user is not None:
        if user.is_active:
            login(request, user)

            return HttpResponseRedirect('/p/')
        else:
            pass
    else:
        next_url = ''
        if request.GET.has_key('next'):
            next_url = request.POST['next']

        return HttpResponseRedirect('/accounts/login/?next=%s' % next_url)

def logout_handler(request):
    logout(request)
    return HttpResponseRedirect('/p/')
